<template>
  <!-- // 地图 -->
  <div class="homePageCards1">
    <div class="full-box" @click="fullscreen">
      <img :src="isFullscreen ? imgUrl2 : imgUrl1" alt="" />
      <span>{{isFullscreen?'返回':'全屏'}}</span>
    </div>
    <div id="warrmap" style="width: 100%; height: 100%"></div>
    <div id='layercards'></div>
  </div>
</template>
<script>
import sjccKey from "@/config/sjmapkey";
import resourceJson from "./map";
export default {
  name: "ResourceMap",
  components: {},
  props: {
    mapCenter: {
      type: Array,
      default: () => [112.96730140947924, 30.574022147218216]
    },
    mapZoom: {
      type: Number,
      default: 8
    }
  },
  data: function () {
    return {
      map: null, // 基础地图
      imgUrl1: require("@/assets/img/full.png"),
      imgUrl2: require("@/assets/img/nofull.png"),
      FullScreen: false,
      isFullscreen: false
    };
  },
  beforeDestroy() {
    this.map && this.map.remove();
    this.map = null;
    this.$eventBus.$off("createlayer");
  },
  mounted() {
    this.initLocalMap();
    window.addEventListener("resize", this.onresize);
  },
  methods: {
    fullscreen() {
      // 进入全屏
      var docElm = document.querySelector(".homePageCards1"); // 指定容器id
      if (!this.FullScreen) {
        // 兼容W3C
        if (docElm.requestFullscreen) {
          docElm.requestFullscreen();
        } else if (docElm.mozRequestFullScreen) {
          // 兼容FireFox
          docElm.mozRequestFullScreen();
        } else if (docElm.webkitRequestFullScreen) {
          // 兼容Chrome等
          docElm.webkitRequestFullScreen();
        } else if (docElm.msRequestFullscreen) {
          docElm.msRequestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      }
      this.FullScreen = !this.FullScreen;
    },
    initLocalMap() {
      const that = this;
      SGMap.tokenTask.login(sjccKey.appkey, sjccKey.appsecret).then((res) => {
        this.map = new SGMap.Map({
        // 地图绑定的DOM元素ID
          container: "warrmap",
          // 地图样式
          style: "aegis://styles/aegis/Streets",
          // 默认缩放层级
          zoom: 6,
          // 地图中心点
          center: [114.36730140947924, 30.574022147218216],
          // 地图默认字体
          localIdeographFontFamily: "Microsoft YoHei"
        });

        this.map.on("load", function (e) {
        // 添加一个geojson类型的数据源，并把cluster属性设置为true，sdk会主动添加point_count、point_count_abbreviated属性到这份数据中
        // point_count是当前聚合点个数，point_count_abbreviated聚合点个数的简写
          // 初始化Popup
          that.popupDOM = new SGMap.Popup({
          // 是否显示关闭按钮
            closeButton: false,
            closeOnClick: false,
            offset: {
              bottom: [0, 0]
            }
          });
          that.map.addSource("themeData", {
            type: "geojson",
            data: resourceJson,
            cluster: true,
            clusterMaxZoom: 12, // 最大聚类层级
            clusterRadius: 100 // 聚合点半径，默认50
          });
          that.map.addLayer({
            id: "clusters",
            type: "circle",
            source: "themeData",
            filter: ["has", "point_count"],
            paint: {
            // 使用step表达式，用于分段匹配圆点的颜色和半径
            // 根据当前"point_count"值匹配对应的内容
            // 默认为"#9faebf"
            // 当大于10小于30时，返回"#3583de"
            // 大于30小于55时，返回"#04b71e"
              "circle-color": [
                "step",
                ["get", "point_count"],
                "#9faebf",
                2,
                "#3583de",
                4,
                "#04b71e",
                6,
                "#ff9800",
                8,
                "#f61402",
                10,
                "#f61402"
              ],
              "circle-radius": [
                "step",
                ["get", "point_count"],
                20,
                50,
                30,
                100,
                35,
                500,
                35,
                2000,
                40,
                5000,
                40
              ],
              "circle-opacity": 0.7,
              "circle-stroke-width": 3,
              "circle-stroke-color": "#ffffff"
            }
          });

          that.map.addLayer({
            id: "clusterCount",
            type: "symbol",
            source: "themeData",
            filter: ["has", "point_count"],
            layout: {
              "text-field": "{point_count_abbreviated}",
              "text-font": ["Microsoft YaHei Regular"],
              "text-size": 14
            },
            paint: {
              "text-color": "#ffffff"
            }
          });

          // 监听聚类图点击，并且根据点击的聚合圆展开
          that.map.on("click", "clusters", function (e) {
            var features = that.map.queryRenderedFeatures(e.point, {
              layers: ["clusters"]
            });
            var clusterId = features[0].properties.cluster_id;

            that.map
              .getSource("themeData")
              .getClusterExpansionZoom(clusterId, function (err, zoom) {
                if (err) return;
                that.map.easeTo({
                  center: features[0].geometry.coordinates,
                  zoom: zoom
                });
              });
          });

          // 画图片点，需要先加载图片 图片路径在页面部署在服务上时可以用相对路径
          var url = require("../../../assets/img/fangzi.png");
          that.map.loadImage(url, function (error, image) {
          // 添加图片到map，可以设置图片id
            that.map.addImage("poi", image);
            that.map.addLayer({
              id: "choicePoi",
              type: "symbol",
              source: "themeData",
              filter: ["!has", "point_count"],
              layout: {
                "icon-image": "poi",
                "icon-size": 0.2
              },
              paint: {
                "text-color": "#555252",
                "text-halo-color": "#FFFFFF",
                "text-halo-width": 1.33333
              }
            });
          });
          that.map.on("mouseenter", "choicePoi", function (e) {
            console.log("789", e);
            const properties = e.features[0].properties;
            that.popupDOM.setLngLat([e.lngLat.lng, e.lngLat.lat]).setHTML(
              `<div style="display:flex;flex-direction:column;">
                <div style="font-size:16px;color:#fff;padding:6px;">${properties.name || "应急物资仓库"}</div>
              </div>`
            ).addTo(that.map);
          });
          that.map.on("mouseleave", "choicePoi", function (e) {
            that.popupDOM.remove();
          });
        });
      });
    },
    onresize(event) {
      // 利用屏幕分辨率和window对象的内高度来判断兼容IE
      const winFlag = window.innerHeight === window.screen.height;
      // 利用window全屏标识来判断 -- IE无效
      const isFull = window.fullScreen || document.webkitIsFullScreen;
      if (isFull === undefined) {
        this.isFullscreen = winFlag;
      } else {
        this.isFullscreen = winFlag || isFull;
      }
      this.FullScreen = this.isFullscreen;
    }
  }
};
</script>

<style scoped lang="less">
.homePageCards1 {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 6px;
  border-radius: 5px;
  #map {
    border-radius: 5px;
  }
}
.full-box {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 700;
  z-index: 9;
  background-color: #fff;
  cursor: pointer;
  padding: 3px 8px;
  border-radius: 5px;
  img {
    width: 15px;
    height: 15px;
    margin-right: 5px;
  }
}
:deep(.sgmap-popup-content) {
  background-color: #46577c !important;
  padding: 0 !important;
}
</style>
